import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../decorator/public.decorator';

// 校验设备id
@Injectable()
export class DeviceIdGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(context: ExecutionContext): boolean | Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    // console.log(context);
    const deviceId = request.deviceId;
    return matchDeviceId(deviceId);
  }
}
function matchDeviceId(deviceId: string): boolean | Promise<boolean> {
  // 创建一个正则表达式来匹配32位十六进制数（不区分大小写）
  const hexRegex = /^[A-Fa-f0-9]{32}$/;
  return hexRegex.test(deviceId);
}
